package com.mgface.zookeeper.curator.function;

import java.util.concurrent.TimeUnit;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.CancelLeadershipException;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class Mater选举 {

	public static void main(String[] args) throws Exception {
		CuratorFramework client = CuratorFrameworkFactory.builder().connectString("localhost:2181")
				.sessionTimeoutMs(10_000).connectionTimeoutMs(10_000).retryPolicy(new ExponentialBackoffRetry(1000, 3))
				.build();
		client.start();
		System.out.println("连接启动完毕");
		String path = "/curator_recipes_master";
		LeaderSelector selector = new LeaderSelector(client, path, new LeaderSelectorListener() {
			
			@Override
			public void stateChanged(CuratorFramework client, ConnectionState state) {
				if(state == ConnectionState.SUSPENDED||state == ConnectionState.LOST){
					throw new CancelLeadershipException();
				}
			}
			
			@Override
			public void takeLeadership(CuratorFramework client) throws Exception {
				System.out.println("成为master角色...");
				System.out.println(client.getChildren().forPath(path));
				TimeUnit.SECONDS.sleep(5);
				System.out.println("完成master操作，释放master权利!");
			}
		});
		selector.autoRequeue();//默认情况下,当LeaderSelectorListener.takeLeadership(CuratorFramework)返回时,此实例不会重新排队.调用此方法将leader选择器置于一种模式，它自身将总是重新排队。
		selector.start();
		TimeUnit.SECONDS.sleep(1_000);
		selector.close();
	}

}
